package com.xn.app.muying;

import android.app.AlertDialog;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xn.app.muying.util.APIMethod;
import com.xn.app.muying.util.Constants;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.concurrent.TimeUnit;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class DengLuActivity extends AppCompatActivity {
    private String TAG=this.getClass().getSimpleName();
    EditText zhanghao, mima;
    Button denglu;
    TextView wangji, zhuce;
    OkHttpClient mOkHttpClient = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_deng_lu);
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(60, TimeUnit.SECONDS)
                .writeTimeout(60, TimeUnit.SECONDS)
                .readTimeout(60, TimeUnit.SECONDS).build();
        zhanghao = (EditText) findViewById(R.id.zhang_hao);
        mima = (EditText) findViewById(R.id.mi_ma);
        denglu = (Button) findViewById(R.id.deng_lu);
        wangji = (TextView) findViewById(R.id.wang_ji);
        zhuce = (TextView) findViewById(R.id.zhu_ce);
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        denglu.setOnClickListener(onClickListener);
        wangji.setOnClickListener(onClickListener);
        zhuce.setOnClickListener(onClickListener);
    }

    View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.deng_lu:
                    String zh = zhanghao.getText().toString();
                    String mm = mima.getText().toString();
                    if (!TextUtils.isEmpty(zh) && !TextUtils.isEmpty(mm)) {
                        denglu(zh, mm);
                    } else {
                        ToastUtil.showToast(DengLuActivity.this, "账号和密码不能为空");
                    }
                    break;
                case R.id.wang_ji:
                    Intent intent1 = new Intent(DengLuActivity.this, YanZhengActivity.class);
                    intent1.putExtra("tag", "2");
                    startActivity(intent1);
                    break;
                case R.id.zhu_ce:
                    Intent intent = new Intent(DengLuActivity.this, YanZhengActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                    break;
            }
        }
    };

    AlertDialog denglu_dialog;
    void denglu(final String zh, final String mm) {
        denglu_dialog = MyAlertDialog.ShowDialog(DengLuActivity.this, R.layout.dialog_loading);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    RequestBody formBody = new FormBody.Builder().add("grant_type", "password")
                            .add("username", zh).add("password", mm)
                            .build();
                    String p="grant_type=password  username="+zh+"  password"+mm;
                    Log.i(TAG, "param==" + p);
                    Request request = new Request.Builder().url(APIMethod.DengLu).post(formBody).build();
                    okhttp3.Response response = mOkHttpClient.newCall(request).execute();
                    int code = response.code();
                    String bodys = response.body().string();
                    //{"error":"invalid_grant","error_description":" 登录失败，用户名或密码错误！"}
                    Log.i(TAG, "code==" + code);
                    Log.i(TAG, bodys);
                    if (code == 200) {
                        Message msg = new Message();
                        msg.what = 0;
                        msg.obj = bodys;
                        handler.sendMessage(msg);
                    } else {
                        Message msg1 = new Message();
                        msg1.what = 1;
                        msg1.obj = bodys;
                        handler.sendMessage(msg1);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 0:
                    denglu_dialog.dismiss();
                    ToastUtil.showToast(DengLuActivity.this, "登录成功");
                    Constants.setStringByName(DengLuActivity.this, "yonghu", "");
                    Constants.setStringByName(DengLuActivity.this, "yonghu", msg.obj.toString());
                    Constants.setBooleanByName(DengLuActivity.this,"isLogin",true);
                    if (MainActivity.mActivity.isFinishing()){
                        startActivity(new Intent(DengLuActivity.this,MainActivity.class));
                    }else{
                        sendBroadcast(new Intent("deng_lu_cheng_gong"));
                    }
                    finish();
                    break;
                case 1:
                    denglu_dialog.dismiss();
                    Type type = new TypeToken<HashMap<String, String>>() {}.getType();
                    HashMap<String, String> errmsg = new Gson().fromJson(msg.obj.toString(), type);
                    ToastUtil.showToast(DengLuActivity.this, errmsg.get("error_description"));
                    break;
            }
        }
    };
}
